/*
    Copyright (C) 2011 Rémi Thebault

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/


#include "taskselectionmodel.h"

TaskSelectionModel::TaskSelectionModel(PC::Cycle *cycle, QObject *parent) :
	QObject(parent),
	m_cycle(cycle),
	m_selectedTask(0),
	m_selectedLink(0)
{
}


void TaskSelectionModel::resetCycle(PC::Cycle *cycle) {
	m_cycle = cycle;
	m_selectedTask = 0;
	m_selectedLink = 0;
}


void TaskSelectionModel::selectTask(PC::Task *task, bool selected) {
	PC::Task* old = m_selectedTask;
	bool trigger = true;
	if (task && selected) {
		if (task != m_selectedTask) {
			m_selectedTask = task;
		}
		else {
			trigger = false;
		}
	}
	else {
		m_selectedTask = 0;
	}
	PC::Link* oldL = m_selectedLink;
	m_selectedLink = 0;
	if (trigger) {
		emit taskSelectionChanged(m_selectedTask, old);
	}
	if (oldL) {
		emit linkSelectionChanged(0, oldL);
	}
}

void TaskSelectionModel::selectLink(PC::Link *link, bool selected) {
	PC::Link* old = m_selectedLink;
	bool trigger = true;
	if (link && selected) {
		if (link != m_selectedLink) {
			m_selectedLink = link;
		}
		else {
			trigger = false;
		}
	}
	else {
		m_selectedLink = 0;
	}
	PC::Task* oldT = m_selectedTask;
	m_selectedTask = 0;
	if (trigger) {
		emit linkSelectionChanged(m_selectedLink, old);
	}
	if (oldT) {
		emit taskSelectionChanged(0, oldT);
	}
}

void TaskSelectionModel::clearSelection() {
	PC::Task* oldT = m_selectedTask;
	m_selectedTask = 0;
	PC::Link* oldL = m_selectedLink;
	m_selectedLink = 0;
	if (oldT) {
		emit taskSelectionChanged(0, oldT);
	}
	if (oldL) {
		emit linkSelectionChanged(0, oldL);
	}
}


void TaskSelectionModel::taskWillDelete(PC::Task *task) {
	if (task && task == m_selectedTask) {
		PC::Task* oldT = m_selectedTask;
		m_selectedTask = 0;
		emit taskSelectionChanged(0, oldT);
	}
}


void TaskSelectionModel::linkWillDelete(PC::Link *link) {
	if (link && link == m_selectedLink) {
		PC::Link* oldL = m_selectedLink;
		m_selectedLink = 0;
		emit linkSelectionChanged(0, oldL);
	}
}
